package wechat

import (
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"

	jsoniter "github.com/json-iterator/go"
)

//UserInfo 用户欣喜
type UserInfo struct {
	Openid    string    `json:"openid"`
	NickName  string    `json:"nickName"`
	Gender    int       `json:"gender"`
	City      string    `json:"city"`
	Province  string    `json:"province"`
	Country   string    `json:"country"`
	AvatarURL string    `json:"avatarUrl"`
	UnionID   string    `json:"unionId"`
	WaterMark WaterMark `json:"watermark"`
}

//PhoneNumber 手机号码struct
type PhoneNumber struct {
	PhoneNumber     string    `json:"phoneNumber"`
	PurePhoneNumber string    `json:"purePhoneNumber"`
	CountryCode     string    `json:"countryCode"`
	WaterMark       WaterMark `json:"watermark"`
}

//LoginMiniapp 获取小程序用户信息
func (w *Wx) LoginMiniapp(encryptedData, iv, code string) (userInfo UserInfo, sessionkey string, err error) {
	code2session, err := w.getSessionkey(code)
	if err != nil {
		return
	}
	decrypted, err := wXBizDataDecrypt(code2session.SessionKey, encryptedData, iv)
	if err != nil {
		return
	}
	err = jsoniter.Unmarshal(decrypted, &userInfo)
	if err != nil {
		return
	}
	sessionkey = code2session.SessionKey
	return
}

//GetSessionkey 获取sessionkey
func (w *Wx) getSessionkey(code string) (code2session Code2sessionResult, err error) {
	url := fmt.Sprintf(miniapptokenurl, w.config.MiniAppid, w.config.MiniAppsecret, code)
	r, err := http.Get(url)
	if err != nil {
		return
	}
	defer r.Body.Close()
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		return
	}
	err = jsoniter.Unmarshal(body, &code2session)
	if err != nil {
		return
	}
	if code2session.ErrorCode > 0 {
		err = errors.New(code2session.ErrorMsg)
		return
	}
	return
}

//GetPhoneNumber 小程序获取手机号码
func (w *Wx) GetPhoneNumber(code, encryptedData, iv string) (phoneNumberStruct PhoneNumber, err error) {
	var code2session Code2sessionResult
	code2session, err = w.getSessionkey(code)
	if err != nil {
		return
	}
	decrypted, err := wXBizDataDecrypt(code2session.SessionKey, encryptedData, iv)
	if err != nil {
		return
	}
	err = json.Unmarshal(decrypted, &phoneNumberStruct)
	if err != nil {
		return
	}
	return
}
